﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace _058
{
    internal class Program
    {
        /// <summary>
        /// 线程实例
        /// 在多线程执行的第一个线程称为主线程，当C#程序开始执行时，将自动创建主线程，而使用Thread
        /// 类创建的线程则称为子线程，你可以使用Thread
        /// </summary>
        /// <param name="args"></param>
        
        public static void CallToChildThread()
        {
            Console.WriteLine("执行子线程");
        }
        public static void CallTo()
        {
            Console.WriteLine("执行子线程");
            //线程暂停5000毫秒
            int sleepfor = 5000;
            Console.WriteLine("子线程暂停：{0}秒",sleepfor/1000);
            Thread.Sleep(sleepfor);
            Console.WriteLine("继续执行子线程");
        }
        public static void CCT()
        {
            try
            {
                Console.WriteLine("执行子线程");
                //计数到10
                for(int counter=0;counter<=10;counter++)
                {
                    Thread.Sleep(5000);
                    Console.WriteLine(counter);
                }
                Console.WriteLine("子线程执行完成");
            }
            catch(ThreadAbortException e)
            {
                Console.WriteLine("线程终止：{0}",e);
            }
            finally
            {
                Console.WriteLine("无法捕获线程异常");
            }
        }
        static void Main(string[] args)
        {
            Thread th = Thread.CurrentThread;
            th.Name = "主线程";
            Console.WriteLine("这是：{0}",th.Name);

            ThreadStart Childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("在Manin函数中创建子线程");
            Thread childThread = new Thread(Childref);
            childThread.Start();

            ThreadStart child = new ThreadStart(CallTo);
            Console.WriteLine("在Main函数中创建主线程");
            Thread ChildThread1= new Thread(child);
            ChildThread1.Start();

            ThreadStart childref2 = new ThreadStart(CCT);
            Console.WriteLine("在Main函数中创建子线程");
            Thread childThread2 = new Thread(childref2);
            childThread2.Start();
            //停止主线程一段时间
            Thread.Sleep(5000);
            //现在终止子线程
            Console.WriteLine("在Main函数中终止子线程");
            //childThread2.Abort();
            Console.ReadKey();
        }
    }
}
